package cn.b.sky.mes.cm.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.cm.model.Calendar;
import cn.b.sky.mes.cm.model.CalendarDay;
import cn.b.sky.mes.cm.model.CalendarPattern;
import cn.b.sky.mes.cm.model.CalendarPatternItem;
import cn.b.sky.mes.cm.model.WorkDayType;
import cn.b.sky.mes.cm.model.condition.CalendarCondition;
import cn.b.sky.mes.cm.service.CalendarPatternService;
import cn.b.sky.mes.cm.service.CalendarService;
import cn.b.sky.mes.cm.service.WorkDayTypeService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "/calendar/*")
@Slf4j
public class CalendarController extends SecurityController {
  @Resource
  CalendarService calendarService;

  @Resource
  CalendarPatternService calendarPatternService;

  @Resource
  WorkDayTypeService workDayTypeService;

  @RequestMapping("calendarList")
  public String calendarList(Model model, @ModelAttribute("condition") CalendarCondition calendarCondition,
      String navTabId) {
    calendarCondition.setSiteCode(SecurityContextUtil.getSiteCode());
    if (StringUtils.isEmpty(calendarCondition.getOrderField())) {
      calendarCondition.setOrderField("createDateTime");
    }
    List<Calendar> calendarList = calendarService.selectCalendarByCondition(calendarCondition);
    int count = calendarService.selectCalendarCount(calendarCondition);
    calendarCondition.setData(calendarList);
    calendarCondition.setTotalCount(count);
    model.addAttribute("page", calendarCondition);
    model.addAttribute(NAVTABID, navTabId);
    return "cm/calendar/calendar_list";
  }

  @RequestMapping("validateCalendar")
  @ResponseBody
  public boolean validateCalendar(String calendarCode, Model model) {
    if (!StringUtils.isBlank(calendarCode)) {
      return null == calendarService.selectCalendarByCode(getSiteCode(), calendarCode);
    }
    return true;

  }

  @RequestMapping("addCalendar")
  public String addCalendar(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    List<CalendarPattern> calendarPatterns = calendarPatternService.selectUnLockCalendarPatternList(getSiteCode());
    model.addAttribute("lan", SecurityContextUtil.getLanguageCode());
    model.addAttribute("calendarPatterns", calendarPatterns);
    List<WorkDayType> types = workDayTypeService.selectUnLockWorkDayTypeList(getSiteCode());
    for (CalendarPattern cp : calendarPatterns) {
      List<CalendarPatternItem> items = calendarPatternService.selectCalendarPatternItems(cp.getSiteCode(),
          cp.getCalendarPatternCode());
      cp.setItemsStr(JSONObject.toJSONString(items));
    }
    model.addAttribute("types", types);
    return "cm/calendar/calendar_add";
  }

  @RequestMapping("editCalendar")
  public String editCalendar(Model model, String navTabId, String id) {
    Calendar calendar = calendarService.selectCalendarByCode(getSiteCode(), id);
    model.addAttribute(NAVTABID, navTabId);
    List<CalendarPattern> calendarPatterns = calendarPatternService.selectUnLockCalendarPatternList(getSiteCode());
    if (calendarPatterns == null) {
      calendarPatterns = new ArrayList<CalendarPattern>();
    }
    if (calendar.getCalendarPatternLock() != null && calendar.getCalendarPatternLock() == 1) {
      CalendarPattern cp = new CalendarPattern();
      cp.setSiteCode(getSiteCode());
      cp.setCalendarPatternCode(calendar.getCalendarPatternCode());
      cp.setCalendarPatternText(calendar.getCalendarPatternText());
      cp.setBaseDate(calendar.getBaseDate());
      calendarPatterns.add(cp);
    }
    model.addAttribute("lan", SecurityContextUtil.getLanguageCode());
    model.addAttribute("calendarPatterns", calendarPatterns);
    List<WorkDayType> types = workDayTypeService.selectUnLockWorkDayTypeList(getSiteCode());
    for (CalendarPattern cp : calendarPatterns) {
      List<CalendarPatternItem> items = calendarPatternService.selectCalendarPatternItems(cp.getSiteCode(),
          cp.getCalendarPatternCode());
      cp.setItemsStr(JSONObject.toJSONString(items));
    }
    model.addAttribute("types", types);
    List<CalendarDay> days = calendarService.selectCalendarDaysByCalendarCode(getSiteCode(), id);
    JSONArray json = new JSONArray();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    if (days != null) {
      for (CalendarDay day : days) {
        JSONObject job = new JSONObject();
        job.put("start", sdf.format(day.getCalendarDate()));
        job.put("title", day.getDayTypeText());
        job.put("type", day.getDayTypeCode());
        job.put("typeLock", day.getDayTypeLock());
        json.add(job);
        JSONObject jobBk = new JSONObject();
        jobBk.put("start", sdf.format(day.getCalendarDate()));
        jobBk.put("end", sdf.format(day.getCalendarDate()));
        jobBk.put("rendering", "background");
        jobBk.put("color", day.getDisplayColor());
        json.add(jobBk);
      }
    }
    calendar.setCalendarDaysStr(json.toJSONString());
    model.addAttribute("calendar", calendar);
    return "cm/calendar/calendar_edit";
  }

  @RequestMapping("viewCalendar")
  public String viewCalendar(Model model, String navTabId, String id) {
    Calendar calendar = calendarService.selectCalendarByCode(getSiteCode(), id);
    model.addAttribute(NAVTABID, navTabId);
    List<CalendarPattern> calendarPatterns = calendarPatternService.selectUnLockCalendarPatternList(getSiteCode());
    if (calendarPatterns == null) {
      calendarPatterns = new ArrayList<CalendarPattern>();
    }
    if (calendar.getCalendarPatternLock() != null && calendar.getCalendarPatternLock() == 1) {
      CalendarPattern cp = new CalendarPattern();
      cp.setSiteCode(getSiteCode());
      cp.setCalendarPatternCode(calendar.getCalendarPatternCode());
      cp.setCalendarPatternText(calendar.getCalendarPatternText());
      calendarPatterns.add(cp);
    }
    model.addAttribute("lan", SecurityContextUtil.getLanguageCode());
    model.addAttribute("calendarPatterns", calendarPatterns);
    List<CalendarDay> days = calendarService.selectCalendarDaysByCalendarCode(getSiteCode(), id);
    JSONArray json = new JSONArray();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    if (days != null) {
      for (CalendarDay day : days) {
        JSONObject job = new JSONObject();
        job.put("start", sdf.format(day.getCalendarDate()));
        job.put("title", day.getDayTypeText());
        job.put("type", day.getDayTypeCode());
        json.add(job);
        JSONObject jobBk = new JSONObject();
        jobBk.put("start", sdf.format(day.getCalendarDate()));
        jobBk.put("end", sdf.format(day.getCalendarDate()));
        jobBk.put("rendering", "background");
        jobBk.put("color", day.getDisplayColor());
        json.add(jobBk);
      }
    }
    calendar.setCalendarDaysStr(json.toJSONString());
    model.addAttribute("calendar", calendar);
    return "cm/calendar/calendar_view";
  }

  @RequestMapping("saveCalendar")
  @ResponseBody
  public DWZResult saveCalendar(Model model, String id, Calendar calendar, HttpServletRequest request) {
    if (calendar == null) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    calendar.setSiteCode(getSiteCode());
    if (!StringUtils.isEmpty(calendar.getCalendarDaysStr())) {
      JSONArray json = JSONArray.parseArray(calendar.getCalendarDaysStr());
      List<CalendarDay> days = new ArrayList<CalendarDay>();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      if (json.size() > 0) {
        for (int i = 0; i < json.size(); i++) {
          JSONObject job = json.getJSONObject(i);
          if (job.get("rendering") == null) {
            CalendarDay day = new CalendarDay();
            day.setSiteCode(getSiteCode());
            day.setCalendarCode(calendar.getCalendarCode());
            Date date = null;
            try {
              date = sdf.parse(job.get("start").toString());
            } catch (ParseException e) {
              log.error("{}", e);
            }
            day.setCalendarDate(date);
            day.setDayTypeCode(job.get("type").toString());
            days.add(day);
          }
        }
      }
      calendar.setCalendarDays(days);
    } else {
      calendar.setCalendarDays(null);
    }

    setCreateInfo(calendar);
    if (StringUtils.isEmpty(id)) {
      calendarService.insertCalendar(calendar);
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);
    } else {
      calendarService.updateCalendar(calendar);
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);

    }

  }

  @RequestMapping("deleteCalendar")
  @ResponseBody
  public DWZResult deleteCalendar(Model model, String navTabId, String id, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = calendarService.deleteCalendar(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

}
